<template>
  <div>
    <div class="toolbar">
      <el-select v-model="offeringId" placeholder="开课" filterable clearable style="width: 260px">
        <el-option v-for="o in offeringOptions" :key="o.id" :label="`开课#${o.id} 课程${o.courseId} 班级${o.classId} 学期${o.termId}`" :value="o.id" />
      </el-select>
      <el-button type="primary" @click="load">查询成绩项</el-button>
      <el-button type="success" @click="openCreate" :disabled="!offeringId">新增成绩项</el-button>
    </div>

    <el-table :data="items" stripe style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="type" label="类型" width="160" />
      <el-table-column prop="maxScore" label="满分" width="120" />
      <el-table-column prop="weight" label="权重(%)" width="120" />
      <el-table-column prop="standardJson" label="评分标准JSON" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">编辑</el-button>
          <el-popconfirm title="确认删除该成绩项？" @confirm="doDelete(row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="editing ? '编辑成绩项' : '新增成绩项'" width="680">
      <el-form :model="form" label-width="120px">
        <el-form-item label="开课">
          <el-select v-model="form.offeringId" placeholder="选择开课" filterable style="width: 260px">
            <el-option v-for="o in offeringOptions" :key="o.id" :label="`开课#${o.id} 课程${o.courseId} 班级${o.classId} 学期${o.termId}`" :value="o.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.type" placeholder="选择">
            <el-option label="平时" value="REGULAR" />
            <el-option label="期中" value="MIDTERM" />
            <el-option label="期末" value="FINAL" />
            <el-option label="实验" value="LAB" />
            <el-option label="作业" value="ASSIGNMENT" />
            <el-option label="考勤" value="ATTENDANCE" />
          </el-select>
        </el-form-item>
        <el-form-item label="满分"><el-input-number v-model="form.maxScore" :min="0" :max="1000" /></el-form-item>
        <el-form-item label="权重(%)"><el-input-number v-model="form.weight" :min="0" :max="100" /></el-form-item>
        <el-form-item label="评分标准JSON"><el-input v-model="form.standardJson" type="textarea" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listScoreItems, createScoreItem, updateScoreItem, deleteScoreItem, type ScoreItem } from '@/api/grades/scoreItems'
import { listOfferings, type CourseOffering } from '@/api/grades/offerings'

const loading = ref(false)
const items = ref<ScoreItem[]>([])
const offeringId = ref<number | undefined>(undefined)

const dialogVisible = ref(false)
const editing = ref(false)
const form = ref<ScoreItem>({})
const offeringOptions = ref<CourseOffering[]>([])

async function load() {
  if (!offeringId.value) {
    ElMessage.warning('请先选择开课')
    return
  }
  loading.value = true
  try {
    items.value = await listScoreItems({ offeringId: offeringId.value })
  } finally {
    loading.value = false
  }
}

function openCreate() {
  editing.value = false
  form.value = { offeringId: offeringId.value }
  dialogVisible.value = true
}

function openEdit(row: ScoreItem) {
  editing.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

async function submit() {
  try {
    if (editing.value && form.value.id) {
      await updateScoreItem(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createScoreItem(form.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '操作失败')
  }
}

async function doDelete(id?: number) {
  if (!id) return
  try {
    await deleteScoreItem(id)
    ElMessage.success('已删除')
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '删除失败')
  }
}

async function loadOfferingOptions() {
  try {
    offeringOptions.value = await listOfferings({})
  } catch {}
}

onMounted(() => {
  loadOfferingOptions()
})
</script>

<style scoped>
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
}
</style>